<?php
/*
 * Mike add
 */
function getTPImgUrl($str,$type=0) {
	//type 为0，取原始图;为1取缩略图
	if($type == 0) {
		return WEB_PUBLIC_PATH.substr($str,8);
	}
	else {
		$original = basename($str);
		return WEB_PUBLIC_PATH.substr(dirname($str).'/'.'thumb_'.$original,8);
	}
}

/*
 * 获取页面摘要描述
*/
function getDesc($var="",$length=200) {
	$desc = strip_tags($var);
	$desc = html_entity_decode($desc,ENT_QUOTES,'UTF-8');
	$desc = str_replace(chr(13),'',$desc);
	$desc = str_replace(chr(10),'',$desc);
	//$desc = substr($desc,0,$length);
	return cutstr($desc,$length);
    //return $desc;
}

function cutstr($string, $length = 100, $dot = ' ...') {
	$charset = 'utf-8';
	$string = preg_replace ('/\s+/m', ' ', $string);
	if (strlen($string) <= $length) {
		return $string;
	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	if (strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while ($n < strlen($string)) {
			$t = ord($string[$n]);
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n++;
				$noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n++;
			}
			if ($noc >= $length) {
				break;
			}
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
	} else {
		for ($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

/**
 * 得到配置变量的一维数组
 */
function getConfigVal($key,$title) {
    $result = C($title);
    if(empty($key)) {
        return $result[0];
    }
    else {//可能遇到0时会有问题TODO
        return $result[$key];
    }
}

function getModelName($id,$model) {
    $id = intval($id);
    return M($model)->where('id='.$id)->getField('name');
}

function getFitment($i){
    switch ($i) {
        case 1:
            return "普通";
            break;
        case 2:
            return "精装";
            break;
        default:
            return "豪华";
    }
}

function getProp_type($i) {
    switch ($i) {
        case 1:
            return "住宅";
            break;
        case 2:
            return "酒店";
            break;
        default:
            return "公寓";
    }
}

/**
 *获取房型的默认最小价格
 * @param <type> $id 房型ID
 */
function getDefaultPrice($id) {
    $Price = M('Price');
    $condition = array();
    $condition['house_id'] = $id;
    $condition['start_day'] = 0;
    $condition['end_day'] = 0;
    $default = $Price ->field('price')->where($condition)->find();
    return $default['price'];
}
function chkemail($email) {
	return strlen($email) > 6 && preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $email);
}

function toDate($time, $format = 'Y-m-d H:i:s') {
    if (empty ( $time )) {
        return '';
    }
    $format = str_replace ( '#', ':', $format );
    return date ($format, $time );
}

/**
 *返回回复的内容或ID号等
 * @param <type> $id
 * @param <type> $type
 * @return <type>
 */
function getAnswerInfo($id,$type){
    if(empty($type)){
         return M('Comment')->where('parent ='.intval($id))->getField('content');
    }
    else{
        return M('Comment')->where('parent ='.intval($id))->getField($type);
    }
}

/**
 * 返回房间的编号
 * @param <type> $rooms 房间ID，以,隔开
 */
function getRoomNo($rooms) {
    $room_id = explode(',', $rooms);
    $room_no = '';
    $Room = M('Room');
    foreach ($room_id as $val) {
        $room_no .= $Room ->where('id ='.$val)->getField('room_no')." ,";
    }
    return $room_no;
}

/**
 *返回产品的名称（公寓或房型）
 * @param <type> $type 0房型,1公寓
 */
function getPName($pid,$type){
  $model = $type==0 ? 'House':'Hotel';
  return getModelName($pid, $model);
}

/**
 +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码
 * 默认长度6位 字母和数字混合 支持中文
 +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function rand_string($len = 6, $type = '', $addChars = '') {
	$str = '';
	switch ($type) {
		case 0 :
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
			break;
		case 1 :
			$chars = str_repeat ( '0123456789', 3 );
			break;
		case 2 :
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
			break;
		case 3 :
			$chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
			break;
		default :
		// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
			$chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
			break;
	}
	if ($len > 10) { //位数过长重复字符串一定次数
		$chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 );
	}
	if ($type != 4) {
		$chars = str_shuffle ( $chars );
		$str = substr ( $chars, 0, $len );
	} else {
		// 中文随机字
		for($i = 0; $i < $len; $i ++) {
			$str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 );
		}
	}
	return $str;
}
function pwdHash($password, $type = 'md5') {
	return hash ( $type, $password );
}

/**
 * 一次给多个用户发送邮件,
 */
function multiSendMail($subject='',$message='',$from='',$to='') {
	$from = preg_replace('/\v*/', '', $from);
	if (empty($from) || empty($to)) {
		return false;
	}
	$to = explode(',',preg_replace('/\v*/', '', $to.','.C('SERVEEMAIL')));
	foreach($to as $value) {
		if (!empty($value)) {
			sendMail($subject,$message,$from,$value);
		}
	}
}

// 参数设置 string $subject, string $message, 'name <name@server.suffix>' $from, 'name1 <name1@server1.suffix>,name2 <name2@server2.suffix>....' $to
function sendMail($subject='',$message='',$from='',$to='') {
    if (empty($subject) || empty($to)) {
        //throw new Exception('参数错误');
            log::write("发邮件时，标题为空或收件人为空");
            return;
    }
    $mail = array(
            'charset' => "UTF-8",
            'adminemail' => "info@okhome.cn",
            'sendmail_silent' => 1,
            'maildelimiter' => 1,
            'mailusername' => 1,
            'mailsubject' => $subject,
            'mailmessage' => $message,
            'from' => $from,
            'mailto' => $to,
            'server' => "smtp.exmail.qq.com",
            'port' => 25,
            'mailsend' => 2,
            'auth' => 1,
            'auth_username' => 'info@okhome.cn',
            'auth_password' => 'ok62770636',
    );

    if($mail['sendmail_silent']) {
        error_reporting(0);
    }

    $email_from = $mail['from'];
    $email_to = $mail['mailto'];
    $charset = isset($mail['charset']) ? $mail['charset'] : 'UTF-8';
    $maildelimiter = $mail['maildelimiter'] == 1 ? "\r\n" : ($mail['maildelimiter'] == 2 ? "\r" : "\n");
    $mailusername = isset($mail['mailusername']) ? $mail['mailusername'] : 1;

    $email_subject = '=?'.$charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', $mail['mailsubject']))).'?=';
    $email_message = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $mail['mailmessage'])))))));

    $email_from = $email_from == '' ? '=?'.$charset.'?B?'.base64_encode('管理员')."?= <".$mail['adminemail'].">" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.$charset.'?B?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);

    foreach(explode(',', $email_to) as $touser) {
        $tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($mailusername ? '=?'.$charset.'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;
    }
    $email_to = implode(',', $tousers);

    $headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Mailman{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=$charset{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";

    $mail['port'] = $mail['port'] ? $mail['port'] : 25;

    if($mail['mailsend'] == 1 && function_exists('mail')) {

        @mail($email_to, $email_subject, $email_message, $headers);

    } elseif($mail['mailsend'] == 2) {

        if(!$fp = fsockopen($mail['server'], $mail['port'], $errno, $errstr, 30)) {
            throw new Exception('SMTP ', "($mail[server]:$mail[port]) CONNECT - Unable to connect to the SMTP server", 0);
        }
        stream_set_blocking($fp, true);

        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != '220') {
            throw new Exception('SMTP '."$mail[server]:$mail[port] CONNECT - $lastmessage");
        }

        fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." Mailman\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
            throw new Exception('SMTP '."($mail[server]:$mail[port]) HELO/EHLO - $lastmessage");
        }

        while(1) {
            if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
                break;
            }
            $lastmessage = fgets($fp, 512);
        }

        if($mail['auth']) {
            fputs($fp, "AUTH LOGIN\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 334) {
                throw new Exception('SMTP '."($mail[server]:$mail[port]) AUTH LOGIN - $lastmessage");
            }

            fputs($fp, base64_encode($mail['auth_username'])."\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 334) {
                throw new Exception('SMTP '."($mail[server]:$mail[port]) USERNAME - $lastmessage");
            }

            fputs($fp, base64_encode($mail['auth_password'])."\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 235) {
                throw new Exception('SMTP '."($mail[server]:$mail[port]) PASSWORD - $lastmessage");
            }

            $email_from = $mail['from'];
        }

        fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 250) {
            fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 250) {
                throw new Exception('SMTP '."($mail[server]:$mail[port]) MAIL FROM - $lastmessage");
            }
        }

        $email_tos = array();
        foreach(explode(',', $email_to) as $touser) {
            $touser = trim($touser);
            if($touser) {
                fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
                $lastmessage = fgets($fp, 512);
                if(substr($lastmessage, 0, 3) != 250) {
                    fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
                    $lastmessage = fgets($fp, 512);
                    throw new Exception('SMTP '."($mail[server]:$mail[port]) RCPT TO - $lastmessage");
                }
            }
        }

        fputs($fp, "DATA\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 354) {
            throw new Exception('SMTP '."($mail[server]:$mail[port]) DATA - $lastmessage");
        }

        $headers .= 'Message-ID: <'.date('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";
        //将gmdate改为date，以使用当前时区
        fputs($fp, "Date: ".date('r')."\r\n");
        fputs($fp, "To: ".$email_to."\r\n");
        fputs($fp, "Subject: ".$email_subject."\r\n");
        fputs($fp, $headers."\r\n");
        fputs($fp, "\r\n\r\n");
        fputs($fp, "$email_message\r\n.\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 250) {
            throw new Exception('SMTP '."($mail[server]:$mail[port]) END - $lastmessage");
        }

        fputs($fp, "QUIT\r\n");

    } elseif($mail['mailsend'] == 3) {

        ini_set('SMTP', $mail['server']);
        ini_set('smtp_port', $mail['port']);
        ini_set('sendmail_from', $email_from);

        @mail($email_to, $email_subject, $email_message, $headers);

    }
}

function sendMsg($msg="",$to="13524320908",$from = "13524320908",$pwd="lm29723949") {
    $alert_value = M('Configure')->where('var_name = "alert_type" ')->getField('value');
    if($alert_value != 1){
        return false;//不发送短信
    }
    if(!isset($msg)){
        $msg = '上海好家服务公寓(OKHome.cn)有新交易动态，请注意查看!';
    }
    import ('Admin.ORG.PHPFetion');
    $fetion = new PHPFetion($from, $pwd); // 手机号、飞信密码
    $fetion->send($to, $msg); // 接收人手机号、飞信内容
    Log::write("飞信发送信息:".$to.$msg);
    return true;
}
/**
 *
 * @param <type> $code
 * @param <type> $model
 * @return <type>
 */
function getAddressName($code,$model){
    $map = array();
    $name = "";
    switch ($model){
        case "province":
            $map['prov_code'] = $code;
            $name = "prov_name";
            break;
        case "city":
            $map['city_code'] = $code;
            $name = "city_name";
            break;
        case "country":
            $map['coun_code'] = $code;
            $name = "coun_name";
            break;
    }
    $result = M($model)->where($map)->field($name)->find();
    return $result[$name];

}

function getHotelAddress($hotel_id){
    $hotel = M('Hotel')->where('id='.$hotel_id)->find();
    return getAddressName($hotel['prov_code'],'province').getAddressName($hotel['coun_code'],'country').$hotel['address'];

}

/**
*@obj message,order
**obj_id
**@value :new value
**/
function updateLogStatus($obj,$obj_id,$value){
    $msg_log = M('Msg_log');
     if(0 == ($count =  $msg_log->where('obj = "'.$obj.'" and obj_id = '.$obj_id)->count('id') ) ){
        //dump($msg_log->getLastSql());exit;
        $data = array(
            'obj' => $obj,
            'obj_id' => $obj_id,
            'is_read' => $value);
        $msg_log->add($data);
     }else{
        $msg_log->where('obj = "'.$obj.'" and obj_id = '.$obj_id)->setField('is_read',$value);
     }

}


//返回该对象是否被阅读过，若已阅读，则返回true,or false;
function is_read($obj,$obj_id){
    $msg_log = M('Msg_log');
    $rs = $msg_log->where('obj = "'.$obj.'" and obj_id = '.$obj_id.' and is_read = 1')->find();
    if($rs)
        return true;
    else
        return false;
}

//if is not read yet,return class=out,display bold style; 
function readClass($obj,$obj_id,$i){
    $is_read = is_read($obj,$obj_id);
    if(!$is_read){
        if ($i%2 == 0 )
            return "class='out tdpink'";
        else
            return "class='out white'";
    }
        
    else{
        if ($i%2 == 0)
             return "class='tdpink'";
        else
            return "class='white'";
    }
       
}
?>
